import allure
import pytest
from playwright.sync_api import sync_playwright, Page


class ReportPage:
    # 初始化page
    __page: Page = None

    @classmethod
    def get(cls):
        return cls.__page

    @classmethod
    def set(cls, page):
        cls.__page = page


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()
    print(rep)
    # 以下为实现异常截图的代码
    # rep.when可选参数有call、setup、teardown,
    # call表示为用例执行环节、setup、teardown为环境初始化和清理环节
    # 这里只针对用例执行且失败的用例进行异常截图
    if rep.when == "call" and rep.failed:
        allure.attach(ReportPage.get().screenshot(), '异常截图', allure.attachment_type.JPG)
        # ReportPage.get().wait_for_timeout(3000)
        # allure.attach(ReportPage.get().screenshot(), '异常截图', allure.attachment_type.PNG)


@pytest.fixture(scope='class')
def create_page():
    print('启动playwright服务')
    # 实例化playwright
    playwright = sync_playwright().start()
    # 打开chrome浏览器,headless默认是True,无头模式,这里设置为False方便查看效果
    browser = playwright.chromium.launch(headless=False, args=["--start-maximized"])
    # 打开content
    content = browser.new_context(no_viewport=True)
    # 设置默认等待时间
    content.set_default_timeout(60000)
    # 打开一个窗口页面
    page = content.new_page()
    ReportPage.set(page)
    yield page
    print('关闭playwright服务')
    # 关闭page、context、browser
    page.close()
    content.close()
    browser.close()
    # 关闭服务
    playwright.stop()


@pytest.fixture(scope='function', autouse=True)
def fun02():
    print('------开始执行测试用例------')
